package com.app.draft.service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.guice.ApplicationScoped;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.app.sso.client.servlet.UserBean;
import com.app.util.StringUtil;

@Service("draftService")
//Service层
@RemoteProxy(name = "draftService")
//远程dwr组建
@ApplicationScoped
public class DraftServiceImpl implements DraftService {
	private Logger log = Logger.getLogger(DraftServiceImpl.class);
	private Pattern cn = Pattern.compile("[\u4e00-\u9fa5]");
	private Pattern zhang = Pattern.compile("^\\s*(第.+章)(.*[^\\s+^\\d+]*)$");
	private Pattern tiao = Pattern.compile("^\\s*第.+条.*[^\\s+^\\d+]*$");
	
	@Resource(name="sqlMapClientTemplate")
	private SqlMapClientTemplate st;

	public Map queryTitleById(String id){
		return (Map)st.queryForObject("draft.queryTitleById", id);
	}
	public List queryItemByDirectory(String dirid){
		return st.queryForList("draft.queryItemByDirectory",dirid);
	}
	public List queryDirectory(String titleid){
		return st.queryForList("draft.queryDirectory",titleid);
	}
	@Override
	public Map findDraft(Map map, HttpSession se) {
		UserBean user = (UserBean)se.getAttribute("CNNAME");
		String role = user.getRoleID();
		int pageCount = Integer.parseInt((String)map.get("pageCount"));
		int curPage = Integer.parseInt((String)map.get("curPage"))-1;
		String itemType = (String)map.get("itemType");
		if("5".equals(role) || "9".equals(role)){
			map.put("pubuser", true);
		}else{
			map.put("departid", user.getArea().split(","));
		}
		if("1".equals(itemType) || "2".equals(itemType)){
			map.put("pubmes", 1);
		}else{
			map.put("pubmes", 0);
		}
		map.put("start", curPage*pageCount+1);
		map.put("end", (curPage+1)*pageCount);
		List list = st.queryForList("draft.findDraft", map);
		int count = (Integer)st.queryForObject("draft.findDraft_count", map, Integer.class);
		Map m = new HashMap();
		m.put("totalPage", count%pageCount==0?count/pageCount:(count/pageCount)+1);
		m.put("list", JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd"));
		return m;
	}
	@Transactional
	public void saveDraft(Map param,File file){
		String filename = file.getName();
		String suf = filename.substring(filename.lastIndexOf(".")+1);
		List<Map> doc = null;
		if("doc".equalsIgnoreCase(suf)){
			doc = this.parseDoc(file);
		}else if("docx".equalsIgnoreCase(suf)){
			doc = this.parseDocx(file);
		}
		if(doc != null){
			String titleid = StringUtil.createKey();
			param.put("id", titleid);
			
			List zhanglist = new ArrayList();
			List tiaolist = new ArrayList();
			for(Map map : doc){
				String zj = (String)map.get("zhang");
				String zjname = (String)map.get("zhangtext");
				String zhangid = StringUtil.createKey();
				Map zhang = new HashMap();
				zhang.put("id", zhangid);
				zhang.put("zj", zj);
				zhang.put("zjname", zjname);
				zhang.put("titleid", titleid);
				zhanglist.add(zhang);
				
				Map tiao = (Map)map.get("tiao");
				for(Object key : tiao.keySet()){
					String t = (String)tiao.get(key);
					Map tm = new HashMap();
					tm.put("id", StringUtil.createKey());
					tm.put("zjsm", t);
					tm.put("dirid", zhangid);
					tm.put("titleid", titleid);
					tiaolist.add(tm);
				}
			}
			st.insert("draft.insert_zqyj_title", param);
			st.insert("draft.insert_zqyj_directory", zhanglist);
			st.insert("draft.insert_zqyj_zjsm", tiaolist);
		}
	}
	
	private List<Map> parseDocx(File file){
		List<Map> list = new ArrayList();
		try {
			XWPFDocument doc = new XWPFDocument(new FileInputStream(file));
			Iterator<XWPFParagraph> it = doc.getParagraphsIterator();
			while (it.hasNext()) {
				XWPFParagraph p = it.next();
				String s = p.getText().trim();
				parseText(list, s);
			}
		} catch (Exception e) {
			log.error("",e);
		}
		return list;
	}
	private List<Map> parseDoc(File file){
		List<Map> list = new ArrayList();
		try {
			HWPFDocument doc = new HWPFDocument(new FileInputStream(file));
			Range range = doc.getRange();
			int pnum = range.numParagraphs();
			for (int i = 0; i < pnum; i++) {
				Paragraph p = range.getParagraph(i);
				String s = p.text().trim().replaceAll("\\r", "");
				parseText(list, s);
			}
		} catch (Exception e) {
			log.error("",e);
		}
		return list;
	}
	private void parseText(List<Map> list,String s) {
		if(cn.matcher(s).find()){
			Matcher matcher = zhang.matcher(s);
			if(matcher.find()){
				Map m = new LinkedHashMap();
				m.put("zhang",matcher.group(1));
				m.put("zhangtext",matcher.group(2));
				Map tiao = new LinkedHashMap();
				m.put("tiao", tiao);
				list.add(m);
			}else if(tiao.matcher(s).find()){
				if(list.isEmpty()){
					Map m = new LinkedHashMap();
					m.put("zhang","默认章");
					m.put("zhangtext","");
					Map tiao = new LinkedHashMap();
					m.put("tiao", tiao);
					list.add(m);
				}
				Map mm = list.get(list.size()-1);
				Map tiao = (Map)mm.get("tiao");
				int j = tiao.size();
				tiao.put(j, s);
			}else{
				if(!list.isEmpty()){
					Map mm = list.get(list.size()-1);
					Map tiao = (Map)mm.get("tiao");
					if(tiao.isEmpty()){
						mm.put("zhangtext", mm.get("zhangtext")+s);
					}else{
						int j = tiao.size()-1;
						tiao.put(j, tiao.get(j)+s);
					}
				}
			}
		}
	}
}
